<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="68px">
      <el-form-item label="执行人" prop="username">
        <el-input
          v-model="queryParams.where.username"
          placeholder="请输入执行人"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <!-- <el-form-item label="用户名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入用户名"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="端口" prop="status">
        <el-select v-model="queryParams.status" placeholder="请输入端口" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="margin_bottom_8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:add']"
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:edit']"
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate(undefined)"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:remove']"
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:post:export']"
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col> -->
    </el-row>

    <el-table v-loading="loading" :data="postList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="开始时间" align="center" prop="starttime" :formatter="row=>formatDate(row.starttime)" />
      <el-table-column label="执行人" align="center" prop="username" />
      <el-table-column label="巡逻类型" align="center" prop="type" :formatter="row=>patrolTypes[row.type]" />
      <el-table-column label="巡逻路径" align="center">
        <template slot-scope="scope">
          <div flex="main:center">
            <div v-for="(item,index) in scope.row.patrolpaths" :key="item.id+''+index" class="margin_right_6"><el-tag size="mini">{{ item.name }}</el-tag></div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="执行间隔" align="center" prop="intervals" :formatter="row=>`${row.intervals}小时`" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- <el-dropdown trigger="click" @command="handleCommand($event,scope.row)">
            <el-link class="el-dropdown-link" type="primary" :underline="false">点击</el-link>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item :command="0">修改</el-dropdown-item>
              <el-dropdown-item :command="1">删除</el-dropdown-item>
              <el-dropdown-item :command="2" divided>测试</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown> -->
          <el-button
            v-hasPermi="['system:post:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['system:post:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
    <!-- 添加或修改路径对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px">
      <template>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="开始时间" prop="starttime" required>
            <el-date-picker
              v-model="form.starttime"
              style="width:100%"
              type="date"
              placeholder="选择开始时间"
            />
          </el-form-item>
          <el-form-item label="执行人" prop="usrid" required>
            <div flex="main:justify">
              <treeselect v-model="form.deptId" style="width:49%" :options="deptOptions" placeholder="请选择归属部门" @select="getUsrList" />
              <el-select v-model="form.usrid" style="width:49%" placeholder="请选择执行人">
                <el-option
                  v-for="item in userList"
                  :key="item.id"
                  :label="item.remark"
                  :value="item.userId"
                />
              </el-select>
            </div>
          </el-form-item>
          <el-form-item label="巡逻类型" prop="type" required>
            <el-radio-group v-model="form.type" style="margin-top: 10px;">
              <el-radio v-for="(item,index) in patrolTypes" :key="index" :label="index">{{ item }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="巡逻路径" prop="type" required>
            <el-select v-model="form.patrolpaths" value-key="id" style="width:100%" multiple placeholder="请选择路径">
              <el-option
                v-for="item in pathArr"
                :key="item.id"
                :label="item.name"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="执行间隔" prop="intervals" required>
            <el-input-number v-model="form.intervals" placeholder="执行间隔" /> 小时
          </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
import { queryList, deleteById, addUpdateItem } from '@/api/setting/patrolplan'
import { queryListAll as listPathAll } from '@/api/setting/patrolpath'
import { listUser } from '@/api/system/user'
import { formatDate } from '@/utils'
import { patrolTypes } from '@/const'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
// import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
  name: 'PlanComponent',
  components: { Treeselect },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 路径表格数据
      postList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 状态数据字典
      statusOptions: [],
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        where: {}
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
        // path: [
        //   { required: true, message: '路径不能为空', trigger: 'blur' }
        // ],
        // postSort: [
        //   { required: true, message: '路径不能为空', trigger: 'blur' }
        // ]
      },
      userList: [],
      patrolTypes,
      pathArr: []
    }
  },
  created() {
    this.getList()
  },
  methods: {
    hanldeSelectDpt(a, b) {
      console.log(a, b)
    },
    /** 查询部门下拉树结构 */
    getPathArr() {
      listPathAll().then(res => {
        this.pathArr = res.data
      })
    },
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
      })
    },
    handleData(arr) {
      const result = []
      let id = ''
      arr.forEach((item, index) => {
        item.patrolpaths = [{ pathName: item.pathName, id: item.pathid }]
        if (id === item.id) {
          const found = result.find(subItem => subItem.id === id)
          found.patrolpaths.push({ pathName: item.pathName, id: item.pathid })
        } else {
          result.push(item)
          id = item.id
        }
      })
      return result
    },
    getUsrList({ id }) {
      listUser({ deptId: id }).then(res => {
        this.userList = res.rows
      })
    },
    /** 查询路径列表 */
    getList() {
      this.loading = true
      queryList(this.queryParams).then(response => {
        // this.postList = this.handleData(response.rows.flat())
        this.postList = response.data
        this.total = response.total
        this.loading = false
      })
    },
    // 路径状态字典翻译
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        // id: undefined,
        // path: undefined,
        // name: undefined,
        // postSort: 0,
        // status: '0',
        // remark: undefined,
        type: 0
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.where = {}
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
      this._row = selection[0]
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.getTreeselect()
      this.getPathArr()
      this.title = '添加路径'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      // const id = row.id || this.ids
      this.getTreeselect()
      this.getPathArr()
      const formData = JSON.parse(JSON.stringify(row || this._row))
      // formData.patrolpaths = formData.patrolpaths.map(item => item.id)
      this.form = formData
      this.open = true
      this.title = '修改路径'
      this._row = undefined
      return this.getUsrList({ id: this.form.deptId })
      // getPlan(id).then(response => {
      //   this.form = response.data
      //   Object.assign(this.form, row || this._row)
      //   this.open = true
      //   this.title = '修改路径'
      //   this._row = undefined
      //   return this.getUsrList({ id: this.form.deptId })
      // })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const user = this.userList.find(item => item.userId === this.form.usrid) || {}
          addUpdateItem({ ...this.form, username: user.remark }).then(response => {
            if (response.code === 200) {
              this.msgSuccess(this.form.id ? '修改成功' : '新增成功')
              this.open = false
              this.getList()
            } else {
              this.msgError(response.msg)
            }
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除路径编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        return deleteById(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(function() {})
    },
    /** 导出按钮操作 */
    handleExport() {
      // const queryParams = this.queryParams
      this.$confirm('是否确认导出所有路径数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function() {
        // return exportPlan(queryParams)
      }).then(response => {
        this.download(response.msg)
      }).catch(function() {})
    },
    formatDate
  }
}
</script>
